package com.example.votes.controller;

import com.example.votes.dto.VoteRequest;
import com.example.votes.service.VoteService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@CrossOrigin(origins = "*")
@RestController
@RequestMapping("/votecharactes")
public class VoteController {

    private final VoteService voteService;

    public VoteController(VoteService voteService) {
        this.voteService = voteService;
    }

    @PostMapping
    public Map<String, String> voteCharacter(@RequestBody VoteRequest req, HttpServletRequest request) {

        String ip = getClientIp(request);
        System.out.println("ip: " + ip);

        return voteService.vote(ip, req.getCharacter(), req.getTime());
    }

    public static String getClientIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
            // X-Forwarded-For 可能是：client, proxy1, proxy2
            // 取第一个非 unknown 的值
            String[] parts = ip.split(",");
            for (String part : parts) {
                part = part.trim();
                if (part.length() != 0 && !"unknown".equalsIgnoreCase(part)) {
                    return part;
                }
            }
        }
        ip = request.getHeader("X-Real-IP");
        if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
            return ip;
        }
        // 最后退回到远端地址
        return request.getRemoteAddr();
    }
}